package com.coc.ofmylistener.event.support;

import com.coc.ofmylistener.event.*;

import java.util.Collection;

public class AsynSupportEventPublisher implements EventPublisher {

    private EventStore eventStore;

    private EventHandlerManager manager = null;

    public AsynSupportEventPublisher(){}

    public AsynSupportEventPublisher(EventHandlerManager manager){
        this.manager = manager;
    }

    public AsynSupportEventPublisher(EventHandlerManager manager, EventStore eventStore){
        this.manager = manager;
        this.eventStore = eventStore;
    }

    public void setEventHandlerManager(EventHandlerManager manager){
        this.manager = manager;
    }

    public void setEventStore(EventStore eventStore){
        this.eventStore = eventStore;
    }

    public void publish(Event event) {
        doPublish(event);
    }

    protected void doPublish(Event event) {

        Collection<EventHandler> handlers = manager.getHandlers();

        if (handlers == null){
//            if (logger.isDebugEnabled())
//                logger.debug("No Event Handler");
        }

        for (EventHandler handler : handlers) {

            if (handler.canHandler(event)) {

                try {
                    if (handler.asynchronous()){
                        eventStore.store(new DefaultEventEntity(event));
                    }else{
                        handler.handler(event);
                    }
                } catch (RuntimeException e) {
                   // logger.error("event handling error", e);
                    throw e;
                } catch (Exception ex){
                   // logger.error("event handling error", ex);
                    throw new RuntimeException(ex.getMessage(), ex);
                }
            }
        }
    }

}
